<template>
  <div class="app-container">
    <div class="filter-container">
      <el-select
        v-model="listQuery.status"
        style="width: 150px"
        class="filter-item"
        @change="handleFilter"
      >
        <el-option key="1" label="已启用" :value="'1'" />
        <el-option key="2" label="已停用" :value="'2'" />
        <el-option key label="全部状态" :value="''" />
      </el-select>
      <el-input
        v-model="listQuery.proxy"
        placeholder="请输入代理账号进行搜索"
        style="width: 220px;"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />
      <el-button
       plain size="small"
        v-waves
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handleFilter"
      >搜索</el-button>
      <el-button
       plain size="small"
        v-waves
        class="filter-item btn"
        type="primary"
        icon="el-icon-refresh"
        @click="handleCancel"
      >重置</el-button>
      <el-button
       plain size="small"
        v-waves
        class="filter-item btn"
        type="success"
        icon="el-icon-plus"
        @click="handleCreate"
      >新增代理</el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
    >
      <el-table-column label="序号" align="center" prop="id" width="60" type="index" />
      <el-table-column label="代理账户" min-width="100" align="center">
        <template slot-scope="{row}">
          <span>{{ row.username }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" min-width="120" align="center">
        <template slot-scope="{row}">
          <span>{{ row.remark ? row.remark:'-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="渠道数量" min-width="80" align="center">
        <template slot-scope="{row}">
          <span>{{ row.channel_sum }}</span>
        </template>
      </el-table-column>
      <el-table-column label="万次UV/单价" min-width="220" align="center">
        <template slot-scope="{row}">
          <span v-html="row.price" />
        </template>
      </el-table-column>
      <!-- <el-table-column label="虚拟单价" min-width="80" align="center">
        <template slot-scope="{row}">
          <span>{{ row.virtual_price }}</span>
        </template>
      </el-table-column>-->
      <el-table-column label="已结算金额" min-width="100" align="center">
        <template slot-scope="{row}">
          <span>{{ row.money_sum }}</span>
        </template>
      </el-table-column>
      <el-table-column label="总UV启动量" min-width="100" align="center">
        <template slot-scope="{row}">
          <span>{{ row.uv_sum }}</span>
        </template>
      </el-table-column>
      <el-table-column label="总PV启动量" min-width="100" align="center">
        <template slot-scope="{row}">
          <span>{{ row.pv_sum }}</span>
        </template>
      </el-table-column>
      <el-table-column label="代理状态" min-width="100" align="center">
        <template slot-scope="{row}">
          <el-switch
            v-model="row.status"
            :active-value="'1'"
            :inactive-value="'2'"
            @change="changeProxyStatus(row)"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        min-width="230"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="{row}">
          <el-button type="danger" plain size="small" @click="handleUpdate(row)">编辑</el-button>
          <el-button type="primary" plain size="small" @click="handleLogin(row)">登录</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      class="pageShow"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />
    <pagination
      v-show="total > 0"
      layout="prev, pager, next"
      :small="true"
      class="pageHidden"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />

    <el-dialog
      :title="textMap[dialogStatus]"
      :visible.sync="dialogFormVisible"
      :width="dialogWidth"
    >
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="left"
        label-width="90px"
        class="fullwidth"
      >
        <el-form-item label="账号" :prop="acc">
          <el-input
            v-model="temp.username"
            placeholder="请输入账号"
            :disabled="dialogStatus==='update'"
          />
        </el-form-item>
        <el-tooltip v-model="capsTooltip" content="Caps lock is On" placement="right" manual>
          <el-form-item label="密码" :prop="pwd">
            <el-input
              :key="passwordType"
              ref="password"
              v-model="temp.password"
              :type="passwordType"
              placeholder="请输入密码"
              name="password"
              tabindex="2"
              autocomplete="on"
              @blur="capsTooltip = false"
            />
            <span class="show-pwd" @click="showPwd">
              <svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'" />
            </span>
          </el-form-item>
        </el-tooltip>
        <el-form-item label="默认单价">
          <el-input v-model="temp.price" placeholder="请输入默认单价" />
        </el-form-item>

        <el-form-item label="备注">
          <el-input v-model="temp.remark" placeholder="请输入备注" />
        </el-form-item>
        <div style="text-align: right">
          <el-button plain size="small" @click="dialogFormVisible = false">取消</el-button>
          <el-button
           plain size="small"
            type="primary"
            v-loading='addloading'
            @click="dialogStatus==='create'?addProxyOrqudao():editUserInfo()"
          >确定</el-button>
        </div>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import {
  getProxyList,
  addProxyOrChannel,
  editUserInfo,
  quickLogin,
} from "@/api/admin/admin";
// import {
//   quickLogin,
// } from "@/api/admin/control";addProxyOrqudao
import waves from "@/directive/waves"; // waves directive
import Pagination from "@/components/Pagination"; // secondary package based on el-pagination
import { Message } from "element-ui";
import { setToken, setUser, setType } from "@/utils/auth";

export default {
  name: "Control",
  components: { Pagination },
  directives: { waves },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      acc: "",
      pwd: "",
      pri: "",
      listQuery: {
        page: 1,
        limit: 20,
        proxy: "",
        status: "",
      },
      temp: {
        username: "",
        password: "",
        price: "",
        ladder_price: "1",
        virtual_price: "1",
        remark: "",
      },
      passwordType: "password",
      capsTooltip: false,
      dialogFormVisible: false,
      dialogStatus: "",
      dialogWidth: 0,
      textMap: {
        update: "修改代理",
        create: "新增代理",
      },
      rules: {
        username: [
          { required: true, message: "账号是必需的", trigger: "blur" },
          {
            validator: (rule, value, callback) => {
              if (/^[a-zA-Z0-9]+$/.test(value) === false) {
                callback(new Error("账号只能包含英文和数字"));
              } else {
                callback();
              }
            },
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "密码是必需的", trigger: "blur" },
        ],
        price: [
          { required: true, message: "单价是必需的", trigger: "blur" },
          {
            validator: (rule, value, callback) => {
              if (/^[1-9][0-9]*(\.[0-9]{1,2})?$/.test(value) === false) {
                callback(new Error("请输入一个数字，只支持两位小数"));
              } else {
                callback();
              }
            },
            trigger: "blur",
          },
        ],
      },
      addloading: false
    };
  },
  created() {
    this.getList();
    this.setDialogWidth();
  },
  mounted() {
    window.onresize = () => {
      return (() => {
        this.setDialogWidth();
      })();
    };
  },
  methods: {
    setDialogWidth() {
      const val = document.body.clientWidth;
      const def = 600; // 默认宽度
      if (val < def) {
        this.dialogWidth = "100%";
      } else {
        this.dialogWidth = def + "px";
      }
    },
    //添加代理
    addProxyOrqudao() {
      if (
        this.temp.username === "" ||
        /^[a-zA-Z0-9]+$/.test(this.temp.username) === false
      ) {
        Message({
          message: "账号必须填写且只能包含英文和数字",
          type: "error",
          duration: 2000,
        });
        return;
      }
      if (this.temp.password === "") {
        Message({
          message: "密码必须填写",
          type: "error",
          duration: 2000,
        });
        return;
      }
      if (
        this.temp.price === "" ||
        /^[1-9][0-9]*(\.[0-9]{1,2})?$/.test(this.temp.price) === false
      ) {
        Message({
          message: "默认单价必须填写且最多支持两位小数",
          type: "error",
          duration: 2000,
        });
        return;
      }
      this.addloading = true
      addProxyOrChannel(this.temp).then((response) => {
        if (response.STATUS === 200) {
          this.handleFilter();
          this.dialogFormVisible = false;
          Message({
            message: response.msg || "添加成功",
            type: "success",
            duration: 2000,
          });
        } else {
          Message({
            message: response.msg || "添加失败",
            type: "error",
            duration: 2000,
          });
        }
        this.addloading = false
      });
    },
    getList() {
      this.listLoading = true;
      getProxyList(this.listQuery).then((response) => {
        this.list = response.DATA.list;
        this.total = response.DATA.total;
        this.listLoading = false;
      });
    },
    handleFilter() {
      this.listQuery.page = 1;
      this.getList();
    },
    handleCancel() {
      this.listQuery.page = 1;
      this.listQuery.proxy = "";
      this.getList();
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        username: "",
        password: "",
        price: "",
        virtual_price: "1",
        ladder_price: "1",
        remark: "",
        role_id: 2,
      };
    },
    handleCreate() {
      this.resetTemp();
      this.dialogStatus = "create";
      this.dialogFormVisible = true;
    },
    showPwd() {
      if (this.passwordType === "password") {
        this.passwordType = "";
      } else {
        this.passwordType = "password";
      }
      this.$nextTick(() => {
        this.$refs.password.focus();
      });
    },

    handleUpdate(row) {
      this.resetTemp();
      this.temp.id = row.id;
      this.temp.username = row.username;
      this.temp.price = row.price;
      this.temp.virtual_price = row.virtual_price;
      this.temp.ladder_price = row.ladder_price;
      this.temp.remark = row.remark;
      this.dialogStatus = "update";
      this.dialogFormVisible = true;
    },
    //修改代理状态
    changeProxyStatus(row) {
      this.temp.id = row.id;
      this.temp.username = row.username;
      this.temp.price = row.price;
      this.temp.virtual_price = row.virtual_price;
      this.temp.ladder_price = row.ladder_price;
      this.temp.remark = row.remark;
      this.temp.status = row.status;
      this.editUserInfo();
    },
    //编辑代理
    editUserInfo() {
      if (
        this.temp.price === "" ||
        /^[1-9][0-9]*(\.[0-9]{1,2})?$/.test(this.temp.price) === false
      ) {
        Message({
          message: "默认单价必须填写且最多支持两位小数",
          type: "error",
          duration: 2000,
        });
        return;
      }
      editUserInfo({ id: this.temp.id }, this.temp).then((response) => {
        if (response.STATUS === 200) {
          this.dialogFormVisible = false;
          this.getList();
          Message({
            message: response.msg || "修改成功",
            type: "success",
            duration: 2000,
          });
        } else {
          Message({
            message: response.msg || "修改失败",
            type: "error",
            duration: 2000,
          });
        }
      });
    },
    //登录
    handleLogin(row) {
      quickLogin({id:row.id}).then((response) => {
        if (response.STATUS === 200) {
          
          if (response.DATA.user_type == 2) {
            let domin1 = "Admin-Token-daili.ydwhgs.com";
            let domin2 = "user-daili.ydwhgs.com";
            let domin3 = "type-daili.ydwhgs.com";
            setToken(response.DATA.token, domin1);
            setUser(response.DATA, domin2);
            setType("daili", domin3);
            window.open("http://daili.ydwhgs.com/", "_blank");
          } else if (response.DATA.user_type == 3) {
            let domin1 = "Admin-Token-qudao.ydwhgs.com";
            let domin2 = "user-qudao.ydwhgs.com";
            let domin3 = "type-qudao.ydwhgs.com";
            setToken(response.DATA.token, domin1);
            setUser(response.DATA, domin2);
            setType("qudao", domin3);

            window.open("http://qudao.ydwhgs.com/", "_blank");
          }
        } else {
          Message({
            message: response.msg || "获取token失败",
            type: "error",
            duration: 2000,
          });
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.show-pwd {
  position: absolute;
  right: 10px;
  top: 0;
  font-size: 16px;
  color: #ccc;
  cursor: pointer;
  user-select: none;
}
.push {
  display: inline-block;
  width: 20px;
  height: 20px;
  line-height: 20px;
  text-align: center;
  vertical-align: middle;
  cursor: pointer;
  margin-left: 5px;
}
.pageHidden {
  display: none;
}
.btn {
  margin-left: 0;
}
.fullwidth {
  width: 450px;
  margin-left: 50px;
}
@media (max-width: 550px) {
  .pageShow {
    display: none;
  }
  .pageHidden {
    display: block;
  }
  .fullwidth {
    width: 100%;
    margin-left: 0;
  }
}
</style>
